package net.flowas.srs.maven;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
//import org.apache.maven.plugins.annotations.Mojo;
//import org.apache.maven.plugin.Mojo;
import org.codehaus.plexus.util.DirectoryScanner;


/**
 * Says "Hi" to the user.
 * @goal generate
 */
public class GreetingMojo extends AbstractMojo
{
	
	 /**
     * The pattern of the files to be included.
     *
     * @parameter default-value="*.xml"
     */
    private String includes;
    
    /**
     * The target directory to which all output will be written.
     *
     * @parameter expression="${basedir}/target/xmlbasedsrs/xhtml5"
     */
    private File targetDirectory;
    
    /**
     * The directory containing the source DocBook files.
     *
     * @parameter expression="${basedir}/src/xmlbasedsrs"
     */
    private File sourceDirectory;    
	
    public void execute() throws MojoExecutionException
    {    	
    	for(String file:scanIncludedFiles()){
    		String fileName = file.split("\\.")[0];
    		File target = new File(targetDirectory,fileName);
    		if(!target.exists()){
    			target.mkdirs();
    			InputStream url = Thread.currentThread().getContextClassLoader().getResourceAsStream("MATE-INF/resources/xmlbasedsrs.zip");
    	    	try {
					unzip(url,target.getAbsolutePath());
				} catch (IOException e) {
					throw new MojoExecutionException("Unzip exception",e);
				}
    		}
    		for(String xsl:getXslSet()){
    			try {
					FileInJarTransformer.xml_xslt_html(new File(sourceDirectory,file), xsl, new File(target,xsl.split("\\.")[0]+".html"));
				} catch (Exception e) {
					throw new MojoExecutionException("Tranform exception",e);
				}
    		}
    	}
    }
   
    private void unzip(InputStream in,String absolutePath) throws IOException {
		ZipInputStream zi = new ZipInputStream(in);
		ZipEntry entry;
		while ((entry = zi.getNextEntry()) != null) {
			if (entry.isDirectory()) {
				continue;
			}
			File file = new File( absolutePath+"/"
					+ entry.getName());
			if (!file.exists()) {
				file.mkdirs();
			}
			file.delete();
			FileOutputStream out = new FileOutputStream(file);
			int count;
			byte data[] = new byte[1000];
			while ((count = zi.read(data, 0, 1000)) != -1) {
				out.write(data, 0, count);
			}
			out.close();
		}
	}
    private Set<String> getXslSet(){
    	Set<String> xslSet=new HashSet<String>();
    	xslSet.add("demo.xsl");
    	xslSet.add("index.xsl");
    	xslSet.add("list.xsl");
    	xslSet.add("map.xsl");
    	xslSet.add("print.xsl");
    	xslSet.add("nfr.xsl");
    	xslSet.add("tree.xsl");
    	xslSet.add("xmldiff.xsl");
    	xslSet.add("mrproject.xsl");
    	return xslSet;
    }
    
    /**
     * Returns the list of srs files to include.
     */
    private String[] scanIncludedFiles() {
      final DirectoryScanner scanner = new DirectoryScanner();
      scanner.setBasedir(sourceDirectory);
      scanner.setIncludes(getIncludes());
      scanner.scan();
      return scanner.getIncludedFiles();
    }
    
    private String[] getIncludes() {
        String[] results = includes.split(",");
        for (int i = 0; i < results.length; i++) {
            results[i] = results[i].trim();
        }
        return results;
    }    
    
	public void setIncludes(String includes) {
		this.includes = includes;
	}

	public void setTargetDirectory(File targetDirectory) {
		this.targetDirectory = targetDirectory;
	}

	public void setSourceDirectory(File sourceDirectory) {
		this.sourceDirectory = sourceDirectory;
	}
}